package com.springboot.blog.interceptor;

import com.springboot.blog.dto.LayResponse;
import com.springboot.blog.dto.Result;
import com.springboot.util.ToolValidated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ApplicationControllerExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationControllerExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handlerError(HttpServletRequest req, Exception e) {
        // 输出异常信息到控制台
        logger.error(e.getMessage());
        e.printStackTrace();
        return new Result().error(e.getMessage());
    }

    /**
     * <h5>功能: 处理实体类参数校验失败的异常</h5>
     *
     * @param bindingResult bindingResult
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public LayResponse BindException(BindException bindingResult) {
        return ToolValidated.myValidate(bindingResult);
    }
}
